IOS change Language and change Language at runtime

這次主要是要實現,當APP在執行當中,可以靠程式碼動態的去切換語系(以下版本可以切換語言以及圖片)

How to force NSLocalizedString to use a specific language

2F 解法,更換APP的小型資料庫記錄語系的欄位(目前試功能只有在重開APP才會生效)

1
2
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", @"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate

3F解法,設定要讀取的語言包,再從指定的語言包依照Key-Value實作出本地化效果
這個Github iOS-Localization 還蠻像的

我的改良版
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//解除NSLocalizedString巨集定義,並將NSLocalizedString(key,comment)定義成[Language get:(key) alter:nil]
#undef NSLocalizedString
#define NSLocalizedString(key,comment) [Language get:(key) alter:nil]

@implementation Language

static NSBundle *bundle = nil;

+(void)initialize {
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString *current = [[languages objectAtIndex:0] retain];
[self setLanguage:current];

}

/*
example calls:
[Language setLanguage:@"it"];
[Language setLanguage:@"de"];
*/

+(void)setLanguage:(NSString *)l {
NSLog(@"preferredLang: %@", l);
NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
bundle = [[NSBundle bundleWithPath:path] retain];
}

+(NSString *)get:(NSString *)key alter:(NSString *)alternate {
return [bundle localizedStringForKey:key value:alternate table:nil];
}

//Add : 2014/06/05
//Usage : [_imageView setImage:[UIImage imageWithContentsOfFile:[Language getImagePath:@"abc" WithExtension:@"png"]]];
+(NSString *)getImagePath:(NSString *)key WithExtension:(NSString *)extension{
return [bundle pathForResource:key ofType:extension];
}

@end